import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo } from '@/api/user'
import type {
    loginFormData,
    loginResponseData,
    userInfoReponseData,
} from '@/api/user/type'

import { UserState } from '@/store/modules/types/type'
import { constantRouter } from '@/router/routes'
import { GET_TOKEN, REMOVE_TOKEN, SET_TOKEN } from '@/util/token'

const useUserStore = defineStore('User', {
    state: (): UserState => {
        return {
            token: GET_TOKEN(),
            menuRoutes: constantRouter,
            username: '',
            avatar: '',
        }
    },
    actions: {
        //用户登录的方法
        async userLogin(data: loginFormData) {
            //登录请求
            const result: loginResponseData = await reqLogin(data)
            //登录请求:成功200->token
            //登录请求:失败201->登录失败错误的信息
            if (result.code == 200) {
                //pinia仓库存储一下token
                //由于pinia|vuex存储数据其实利用js对象
                this.token = result.data
                //本地存储持久化存储一份
                SET_TOKEN(result.data)
                //能保证当前async函数返回一个成功的promise
                return 'ok'
            } else {
                return Promise.reject(new Error(result.data))
            }
        },
        async reqUserInfo() {
            const result: userInfoReponseData = await reqUserInfo()
            if (result.code == 200) {
                console.log(result)
                this.username = result.data.name
                this.avatar = result.data.avatar
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        userLogout() {
            this.token = ''
            this.username = ''
            this.avatar = ''
            REMOVE_TOKEN()
        },
    },
    getters: {},
})

export default useUserStore
